<template>
  <div class="content-container">
    <div class="item-header">
      <div class="header-title">房东管理</div>
    </div>
    <div class="item-content" v-loading="contentLoading">
      <el-button type="primary" size="default" @click="addOwnerInfo">新增房东信息</el-button>
      <el-form
        v-show="isShowSearchForm"
        class="search-form"
        :inline="true"
        :model="searchOwnerForm"
        :rules="searchOwnerFormRules"
        ref="searchOwnerFormRef"
        label-position="right"
        label-width="auto"
        >
        <el-form-item label="房东ID" prop="id">
          <el-input v-model.trim="searchOwnerForm.id" placeholder="请输入房东ID" clearable/>
        </el-form-item>
        <el-form-item label="房东姓名" prop="ownerName">
          <el-input v-model.trim="searchOwnerForm.ownerName" placeholder="请输入房东姓名" clearable/>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model.trim="searchOwnerForm.phone" placeholder="请输入联系方式" clearable/>
        </el-form-item>
        <el-form-item label="房东类型" prop="OwnerType">
          <el-select v-model="searchOwnerForm.ownerType" placeholder="请选择" clearable>
            <el-option v-for="item in ownerTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="dateTime"
            type="datetimerange"
            :shortcuts="shortcuts"
            :disabled-date="isDateDisable"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            unlink-panels
          />
        </el-form-item> -->
      </el-form>
      <div class="operation-btns">
        <el-button type="primary" @click="searchOwnerList">查询</el-button>
        <el-button @click="resetSearchForm">重置</el-button>
        <el-button v-if="isShowSearchForm" type="primary" link @click="foldOperate"><el-icon class="el-icon--right"><ArrowUp /></el-icon>收起</el-button>
        <el-button v-else type="primary" link @click="foldOperate"><el-icon class="el-icon--right"><ArrowDown /></el-icon>展开</el-button>
      </div>
      <el-table
        :data="ownerList"
        style="width: 100%; margin-top: 20px;"
        :default-sort="{ prop: 'color', order: 'descending' }"
        stripe
        >
        <el-table-column label="房东ID" prop="id" width="100" show-overflow-tooltip/>
        <el-table-column label="房东姓名" prop="ownerName" width="120" show-overflow-tooltip/>
        <el-table-column label="联系方式" prop="phone" width="120" show-overflow-tooltip/>
        <el-table-column label="房东类型" prop="ownerType" width="100" show-overflow-tooltip>
          <template #default="scope">
            <!-- {{Util.findLabelObjByProp(ownerTypeOptions, scope.row.ownerType) }} -->
          </template>
        </el-table-column>
        <el-table-column label="推荐指数" prop="rate" sortable width="190">
          <template #default="scope">
            <el-rate :colors="elRateColor" v-model="scope.row.rate" disabled show-score text-color="#ff9900" score-template="{value} 分"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" show-overflow-tooltip/>
        <el-table-column label="操作" width="140">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="editOwner(scope.row)">编辑</el-button>
            <el-button size="small" type="primary" link @click="deleteOwnerConfirm(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <HPagination
        v-if="ownerListPage.total > 0"
        :pageSize="ownerListPage.pageSize"
        :currentPage="ownerListPage.currentPage"
        :totalSize="ownerListPage.total"
        :pageSizeList="[10, 20, 30, 50]"
        @selectPageSize="ownerListSizeChange"
        @handleCurrentChange="ownerListCurrentChange"
      >
      </HPagination>
    </div>
    <AddEditOwnerDialog ref="addEditOwnerDialogRef" :ownerId="editOwnerId" :ownerInfo="ownerInfo" @refreshOwnerList="getOwnerList" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import dayjs from 'dayjs'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { ownerStore } from '@/stores'
import { ownerTypeOptions, elRateColor } from '@/assets/js/enum'
import AddEditOwnerDialog from '@/components/ownerManage/addEditOwner.vue'
import Util from '@/assets/js/util'

const route = useRoute()
const router = useRouter()
const useOwnerStore = ownerStore()
const contentLoading = ref<boolean>(false)
const searchOwnerFormRef = ref<any>(null)
const isShowSearchForm = ref(true)
const foldOperate = () => {
  isShowSearchForm.value = !isShowSearchForm.value
}

const searchOwnerForm = reactive({
  id: '',
  ownerName: '',
  phone: '',
  ownerType: '',
  remark: '',
  // createTime: [],
})
const searchOwnerFormRules = reactive({
  id: [
    { required: false, message: '请输入房东ID', trigger: 'blur' }
  ],
  ownerName: [
    { required: false, message: '请输入房东姓名', trigger: 'blur' }
  ],
  phone: [
    { required: false, message: '请输入联系方式', trigger: 'blur' }
  ],
  ownerType: [
    { required: false, message: '请选择房东类型', trigger: 'change' }
  ]
})

  /**
   * 时间选择 start
   */
   const getRangeDateTime = (day: number) => {
    const endDate = dayjs().format('YYYY-MM-DD HH:mm:ss')
    const startDate = dayjs().subtract(day, 'day').format('YYYY-MM-DD HH:mm:ss')
    return [startDate, endDate]
  }
  const shortcuts = [
    {
      text: '最近一周',
      value: () => {
        return getRangeDateTime(7)
      }
    },
    {
      text: '最近一个月',
      value: () => {
        return getRangeDateTime(30)
      }
    },
    {
      text: '最近三个月',
      value: () => {
        return getRangeDateTime(90)
      }
    }
  ]
  const range = getRangeDateTime(100)
  const dateTime = ref<any>(range)
  const isDateDisable = (date: any) => {
    return date.getTime() > dayjs()
  }
  /**
   * 时间选择 end
   */

  const ownerList = ref<any>([
    {
      id: '1',
      ownerName: '张三',
      ownerType: 1,
      phone: '13800138000',
      address: '北京市朝阳区',
      remark: '无',
      rate: 1
    },
    {
      id: '2',
      ownerName: '李四',
      ownerType: 2,
      phone: '13800138000',
      address: '北京市朝阳区',
      remark: '无',
      rate: 4
    }
  ])

  // 分页
  const ownerListPage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 1 //TODO: 后端返回
  })
  const ownerListSizeChange = (val: number) => {
    ownerListPage.currentPage = 1
    ownerListPage.pageSize = val
    getOwnerList()
  }
  const ownerListCurrentChange = (val: number) => {
    ownerListPage.currentPage = val
    getOwnerList()
  }

  const editOwnerId = ref<string>('')
  const addEditOwnerDialogRef = ref<any>(null)

  // 查询
  const searchOwnerList = () => {
    getOwnerList()
  }
  // 重置
  const resetSearchForm = () => {
    searchOwnerFormRef.value.resetFields()
    ownerListPage.currentPage = 1
    ownerListPage.pageSize = 10
    getOwnerList()
  }
  // 新增信息
  const addOwnerInfo = () => {
    editOwnerId.value = ''
    addEditOwnerDialogRef.value.openDialog()
  }
  // 编辑信息
  let ownerInfo = ref<any>({})
  const editOwner = (row: any) => {
    ownerInfo.value = row
    addEditOwnerDialogRef.value.openDialog('edit', ownerInfo.value)
  }

  // 删除确认
  const deleteOwnerConfirm = (row: any) => {
    ElMessageBox.confirm(
    '确定删除该条信息吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false,
      closeOnPressEscape: false
    }
  )
    .then(() => {
      deleteOwner(row)
    })
    .catch(() => {
    })
  }
  // 删除信息
  const deleteOwner = (row: { id: string; }) => {
    const params = {
      id: row.id
    }
    useOwnerStore.deleteOwnerInfo(params).then((res: any) => {
      const { state, body } = res
      if (state === 'OK' && body) {
        ElMessage.success('删除成功')
        getOwnerList()
      } else {
        ElMessage.error(res.errorMessage || '删除失败')
      }
    })
    .catch((err: any) => {
      ElMessage.error(err.errorMessage || '删除失败')
    })
  }
  // 获取房东列表
  const getOwnerList = () => {
    contentLoading.value = true
    const params = {
      
    }
    useOwnerStore.getAllOwnerList(params).then((res: any) => {
      const { state, body } = res
      if (state === 'OK') {
        ownerList.value = body.content || []
        ownerListPage.total = body.total || 0
      } else {
        ElMessage.error(res.errorMessage || '获取房东列表失败')
      }
    })
    .catch((err: any) => {
      ElMessage.error(err.errorMessage || '获取房东列表失败')
    })
    .finally(() => {
      contentLoading.value = false
    })
  }

  onMounted(() => {
    getOwnerList()
  })

</script>

<style lang="scss" scoped>
.content-container {
  .item-content {
    .search-form {
      .el-input {
        width: 240px;
      }
      .el-select {
        width: 200px;
      }
    }
  }
}
:deep(.h-row) {
    .h-cell {
      background: #F4F5F7;
      .cell {
        border-left: 1px solid #FFFFFF;
        font-size: 12px;
        color: #333;
      }
      &:first-child {
        .cell {
          border-left: none;
        }
      }
    }
}
</style>
